package com.dyylearn.jdbc.statement_;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.*;
import java.util.Properties;
import java.util.Scanner;

@SuppressWarnings({"all"})
public class PreparedStatement_ {
    public static void main(String[] args) throws Exception {
        Scanner scanner = new Scanner(System.in);

        //让用户输入管理员名和密码
        System.out.print("请输入管理员的名字：");//next() 当接收到 空格或者 单引号就是表示结束
        String admin_name = scanner.nextLine();//如果需要看到sql注入，需要nextLine
        System.out.print("请输入管理员的密码：");
        String admin_pwd = scanner.nextLine();

        //通过Properties对象获取配置文件信息
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.propertise"));
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String driver = properties.getProperty("driver");
        String url = properties.getProperty("url");

        //1.注册驱动
        Class.forName(driver);

        //2.得到连接
        Connection connection = DriverManager.getConnection(url, user, password);

        //3.得到PreparedStatement
        //3.1组织sql，sql语句的问号相当于占位符
        String sql = "select name, pwd from admin where name =? and pwd =?";
        //3.2preparedStatement 对象实现了 PreparedStatement 接口的实现类的对象
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        //3.3给?赋值
        preparedStatement.setString(1, admin_name);
        preparedStatement.setString(2, admin_pwd);

        //执行 select 语句 使用 executeQuery
        //如果执行的是 dml(update,insert,delete) executeUpdate()
        //这里执行executeQuery，不要在写 sq
        ResultSet resultSet = preparedStatement.executeQuery();
        if(resultSet.next()) { // 如果查询到一条记录，则说明管理存在
            System.out.println("恭喜你，登录成功");
        } else {
            System.out.println("登录失败");
        }

        //关闭连接
        resultSet.close();
        preparedStatement.close();
        connection.close();
    }
}
